#!/usr/bin/env python
# Create: 2019/1/10
__author__ = '749B'
"""基于装饰器，执行完毕后停止事件循环"""
from twisted.web.client import getPage, defer
from twisted.internet import reactor

task_list = []
stop_deferred = None


def all_done(arg):
    print("All Done")
    reactor.stop()


def one_done(response):
    print(response)


def check_empty(response, *args, **kw):
    url = kw.get('url')
    if url in running_list:
        running_list.remove(url)
    if not running_list:
        stop_deferred.callback()


@defer.inlineCallbacks
def task():
    global running_list, stop_deferred  # 全局变量
    running_list = url_list.copy()
    for url in url_list:
        deferred = getPage(bytes(url, encoding='utf-8'))
        deferred.addCallback(one_done)
        deferred.addCallback(check_empty, url=url)
        yield deferred
    stop_deferred = defer.Deferred()
    yield stop_deferred


url_list = [
    'http://www.bing.com',
    'http://www.baidu.com',
    'http://edu.51cto.com',
]


ret = task()
ret.addBoth(all_done)

if __name__ == '__main__':
    reactor.run()

